#!/usr/bin/env python3
"""
Cython模块编译脚本

用于编译和安装Cython扩展模块
"""

import os
import sys
import subprocess
import platform
import shutil
from pathlib import Path

def check_dependencies():
    """检查依赖项"""
    print("检查依赖项...")
    
    dependencies = ['cython', 'numpy']
    missing = []
    
    for dep in dependencies:
        try:
            __import__(dep)
            print(f"✓ {dep} 已安装")
        except ImportError:
            missing.append(dep)
            print(f"✗ {dep} 未安装")
    
    if missing:
        print(f"\n缺少依赖项: {', '.join(missing)}")
        print("请先安装: pip install " + " ".join(missing))
        return False
    
    return True

def check_compiler():
    """检查编译器"""
    print("\n检查编译器...")
    
    system = platform.system()
    
    if system == "Windows":
        # 检查Visual Studio编译器
        try:
            result = subprocess.run(['cl'], capture_output=True, text=True,encoding='utf-8',errors='replace')
            print("✓ 找到Microsoft Visual C++编译器")
            return True
        except FileNotFoundError:
            print("✗ 未找到Microsoft Visual C++编译器")
            print("请安装Visual Studio Build Tools或Visual Studio")
            return False
    
    elif system in ["Linux", "Darwin"]:
        # 检查GCC/Clang
        try:
            result = subprocess.run(['gcc', '--version'], capture_output=True, text=True,encoding='utf-8',errors='replace')
            print("✓ 找到GCC编译器")
            return True
        except FileNotFoundError:
            try:
                result = subprocess.run(['clang', '--version'], capture_output=True, text=True,encoding='utf-8',errors='replace')
                print("✓ 找到Clang编译器")
                return True
            except FileNotFoundError:
                print("✗ 未找到GCC或Clang编译器")
                return False
    
    return False

def clean_build():
    """清理构建文件"""
    print("\n清理之前的构建文件...")
    
    patterns_to_remove = [
        "build/",
        "*.c",
        "*.cpp", 
        "*.so",
        "*.pyd",
        "*.dll",
        "__pycache__/",
        "*.pyc"
    ]
    
    for pattern in patterns_to_remove:
        if pattern.endswith('/'):
            # 目录
            if os.path.exists(pattern):
                shutil.rmtree(pattern)
                print(f"  删除目录: {pattern}")
        else:
            # 文件模式
            for file in Path('.').glob(pattern):
                if file.is_file():
                    file.unlink()
                    print(f"  删除文件: {file}")

def build_cython_modules():
    """编译Cython模块"""
    print("\n开始编译Cython模块...")
    
    try:
        # 运行setup.py编译
        cmd = [sys.executable, "setup.py", "build_ext", "--inplace"]
        print(f"执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True,encoding='utf-8',errors='replace')
        
        if result.returncode == 0:
            print("✓ Cython模块编译成功!")
            
            # 列出生成的文件
            print("\n生成的文件:")
            extensions = ['.so', '.pyd', '.dll']
            for ext in extensions:
                for file in Path('.').glob(f"*{ext}"):
                    print(f"  {file}")
            
        else:
            print("✗ Cython模块编译失败!")
            print("\n错误输出:")
            print(result.stderr)
            return False
            
    except Exception as e:
        print(f"✗ 编译过程出错: {e}")
        return False
    
    return True

def test_cython_modules():
    """测试Cython模块"""
    print("\n测试Cython模块...")
    
    try:
        # 测试导入
        from cython_integration import get_cython_engine, check_cython_performance
        
        engine = get_cython_engine()
        print(f"✓ Cython引擎创建成功")
        print(f"  Cython可用: {engine.is_available()}")
        
        if engine.is_available():
            # 性能测试
            print("\n运行性能测试...")
            perf_result = check_cython_performance(1000)
            
            if 'speedup' in perf_result:
                print(f"✓ 性能测试完成，加速比: {perf_result['speedup']}")
            else:
                print("✓ 性能测试完成")
        
        return True
        
    except ImportError as e:
        print(f"✗ 导入Cython模块失败: {e}")
        return False
    except Exception as e:
        print(f"✗ 测试过程出错: {e}")
        return False

def main():
    """主函数"""
    print("=== Cython模块编译和安装 ===")
    
    # 检查依赖项
    if not check_dependencies():
        sys.exit(1)
    
    # 检查编译器
    if not check_compiler():
        sys.exit(1)
    
    # 清理构建文件
    clean_build()
    
    # 编译Cython模块
    if not build_cython_modules():
        sys.exit(1)
    
    # 测试模块
    if not test_cython_modules():
        print("\n⚠ 模块编译成功但测试失败，请检查编译结果")
        sys.exit(1)
    
    print("\n🎉 Cython模块编译和安装完成!")
    print("\n使用方法:")
    print("  from cython_integration import get_cython_engine")
    print("  engine = get_cython_engine()")
    print("  print(engine.get_performance_info())")

if __name__ == "__main__":
    main() 